#include "bezier3.h"

Bezier3::Bezier3(int segs= 60)
{
       recalculate(segs);
}

Bezier3::~Bezier3()
{
        if(coefs)
                delete coefs;
}

void Bezier3::recalculate(int segs)
{
       if (coefs)
               delete coefs;

        coefs = new float[segments*3];

        float interv = 1.0/segments;
        float mu = 0.0f;

        for (int i = 0; i < segments; i++){
            float mu2 = mu*mu;
            float mum1 = 1.0f-mu;
            float mum12 = mum1*mum1;

            coefs[i] = mum12;                
            coefs[i+segments] = mum1*mu;
            coefs[i+segments*2] = mu2;

            mu += interv;
        }
}
p3d Bezier3::getFromSeg(p3d p1,p3d p2,p3d p3,int seg)
{
    p3d tmp;    
    float m1 = coefs[seg];
    float m2 = coefs[seg+segments];
    float m3 = coefs[seg+segments*2];

    tmp.x = p1.x * m1 + p2.x * m2 +  p3.x * m3;
    tmp.y = p1.y * m1 + p2.y * m2 +  p3.y * m3;
    tmp.z = p1.z * m1 + p2.z * m2 +  p3.z * m3;

    return tmp;
};

p3d Bezier3::getFromMu(p3d p1, p3d p2,p3d p3,float mu)
{
    p3d tmp;

    int seg = (int) mu/segments;

    float m1 = coefs[seg];
    float m2 = coefs[seg+segments];
    float m3 = coefs[seg+segments*2];

    tmp.x = p1.x*m1 + p2.x*m2 +  p3.x*m3;
    tmp.y = p1.y*m1 + p2.y*m2 +  p3.y*m3;
    tmp.z = p1.z*m1 + p2.z*m2 +  p3.z*m3;

    return tmp;
};
